package com.xywy.bloodandroid.act;

import java.util.HashMap;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.xywy.bloodandroid.R;
import com.xywy.bloodandroid.base.BaseActivity;
import com.xywy.bloodandroid.bean.User;
import com.xywy.bloodandroid.util.Constants;
import com.xywy.bloodandroid.util.MD5;
import com.xywy.bloodandroid.util.ObserverConstants;
import com.xywy.bloodandroid.util.UIUtil;
import com.xywy.bloodandroid.vollery.GetRequest;
import com.xywy.bloodandroid.vollery.OnVolleyResponseListener;
import com.xywy.bloodandroid.vollery.PostRequest;
import com.xywy.bloodandroid.vollery.VolleyManager;

public class LoginAct extends BaseActivity {

	private RelativeLayout login_button;
	private RelativeLayout left_img;
	private TextView middle_title;
//	private TextView right_title;
	private LinearLayout tobar;
	private ImageView right_img;
	private TextView forget_password;
	
	
	private  static int  MIN_Count=6;
	private static  int MAX_COUNT = 16;

//	private Handler handler = new Handler() {
//		public void handleMessage(android.os.Message msg) {
//			switch (msg.what) {
//			case Task.LOGIN:
//
//				break;
//			}
//		}
//	};
	private EditText login_usename;
	private EditText login_password;

	@Override
	protected void initView(Bundle savedInstanceState) {
		this.setContentView(R.layout.act_login);

		left_img = (RelativeLayout) findViewById(R.id.left_img);
		left_img.setVisibility(View.INVISIBLE);
		middle_title = (TextView) findViewById(R.id.middle_title);
//		right_title = (TextView) findViewById(R.id.right_title);
		right_img = (ImageView) findViewById(R.id.right_img);
		middle_title.setText(getResources().getString(R.string.login));
//		right_title.setVisibility(View.VISIBLE);
//		right_title.setText(getResources().getString(R.string.register));
        
		register = (TextView)findViewById(R.id.regist);
		
		
		forget_password = (TextView) findViewById(R.id.forget_password);

		login_usename = (EditText) findViewById(R.id.login_usename);
		login_password = (EditText) findViewById(R.id.login_password);
		login_button = (RelativeLayout) findViewById(R.id.login_button);
		
		chenck_phone_text = (TextView)findViewById(R.id.chenck_phone_text);
		chenck_phone_img = (ImageView)findViewById(R.id.chenck_phone_img);
		chenck_password_text = (TextView)findViewById(R.id.chenck_password_text);
		chenck_password_img = (ImageView)findViewById(R.id.chenck_password_img);
		
		
		
		login_usename.addTextChangedListener(mTextWatcher);
		login_usename.setSelection(login_usename.length());
		
		
		login_password.addTextChangedListener(PsswordTextWatcher);
		login_password.setSelection(login_password.length());
	}

	@Override
	protected void initListener() {
		left_img.setOnClickListener(this);
		middle_title.setOnClickListener(this);
//		right_title.setOnClickListener(this);
		login_button.setOnClickListener(this);
		forget_password.setOnClickListener(this);
		register.setOnClickListener(this);
	}

	@Override
	protected void initData() {

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.left_img:

			break;
		case R.id.right_title:
//			Intent intent2 = new Intent(this, RegistAct.class);
//			startActivity(intent2);

			break;
		case R.id.forget_password:
			Intent intent1 = new Intent(this, ForgotPasswordAct.class);
			startActivity(intent1);
			break;

		case R.id.login_button:
			//正常流程
			if(checkInfo())
			login();
			//测试
//			User.getIUserInstance().setUserid("46224456");
//			Intent intent=new Intent(LoginAct.this, FrameAct.class);
//			startActivity(intent);
//			finish();
			break;
		case R.id.regist:
			Intent intent2 = new Intent(this, RegistAct.class);
			startActivity(intent2);
			break;
		default:
			break;
		}

	}

	// 登录
		private void login() {
			String phonenum = login_usename.getText().toString().trim();
			final String password = login_password.getText().toString().trim();
			PostRequest<String> postRequest = new PostRequest<String>(Constants.getUrl(
					"kbb","users") + "&type=login", String.class,
					new OnVolleyResponseListener<String>() {
					@Override
					public void onSuccess(String response) {
						UIUtil.DissDialog(context, waittingDialog );
//						User.getInstance(context).setUser(response);
						if(response!=null){
//						if(response.getState()==200){
//							if(response.getUserid() != null){
//								System.out.println(response.getUserid());
//								getUserNameFromServer(response.getUserid());
//							}
//						}else{
//							UIUtil.showToast(context, response.getError());
//						}
						JSONObject object;
						try {
							object = new JSONObject(response);
							int state=object.optInt("state");
							String error = object.optString("error");
							if(state==200){
								User.getInstance(context).setUserid(object.optString("userid"));
								User.getInstance(context).setBirthday(object.optString("birthday"));
								User.getInstance(context).setSex(object.optString("sex"));
								User.getInstance(context).setHeight(object.optString("height"));
								User.getInstance(context).setPhonenum(object.optString("phonenum"));
								User.getInstance(context).setIsregister(object.optString("isregister"));
								User.getInstance(context).setIs_log_sucess(true);
								User.getInstance(context).setPassword(password);
								setIsLogsucess();
								if(User.getInstance(context).getUserid() !=null)
								getUserNameFromServer(User.getInstance(context).getUserid());
								System.out.println("...........|||||"+User.getInstance(context).getUserid());
							}else{
								UIUtil.showToast(context, error);
								User.getInstance(context).setIs_log_sucess(false);
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
							
							
						}
					
					}
					
					private void setIsLogsucess() {
						Intent it = new Intent("is_login_sucessful");  
			             sendBroadcast(it);
					}

					@Override
						public void onError(VolleyError volleyError) {
							UIUtil.DissDialog(context, waittingDialog);
							UIUtil.showToast(context, context.getResources()
									.getString(R.string.network_slow));
							enterActivity(LoginAct.class);
						}
					
					   

			});
			HashMap<String, String> params = new HashMap<String, String>();
			params.put("phonenum", phonenum);// phonenum
			params.put("password", password);// password
			postRequest.setParams(params);
			postRequest.setIsParseJson(false);
			executeRequest(postRequest);

		}


	/**
	 * 获取用户�?
	 */
	private void getUserNameFromServer(String userid){
		try {
			String url = Constants.url+"act=kbb&fun=users&type=pullAccountInfo&tag=wjk&userid="+userid
					   +"&sign="+MD5.md5s(Constants.Sign+Constants.wjkTag);
			Log.e("getnameUrl ", url);
			GetRequest<String> getNameRequest = new GetRequest<String>(
					url, String.class, new OnVolleyResponseListener<String>() {

				@Override
				public void onError(VolleyError volleyError) {
					// TODO Auto-generated method stub
					System.out.println(volleyError.getCause());
					Log.e("getuserName-error", volleyError.getStackTrace().toString());
					enterActivity(LoginAct.class);
				}

				@Override
				public void onSuccess(String response) {
					try {
						JSONObject json = new JSONObject(response);
					    int state = json.optInt("state");
					    if(state == 200){
					    	JSONArray array = json.optJSONArray("accounts");
					    	User.getInstance(context).setAvatar(
									json.optString("avatar"));
					    	for(int i=0;i<array.length();i++){
					    		JSONObject item = (JSONObject) array.get(i);
					    		int accountid =  item.optInt("accountid");
					    		if(accountid == 0){
					    			User.getInstance(context).setAccountstr(item.optString("accountstr"));
					    		
//					    			UserKeeper.saveUserInfo(User.getInstance(context), LoginAct.this);
					    			break;
					    		}
					    	}
					    	enterActivity(MainFragmentAct.class);
					    }else{
					    	enterActivity(LoginAct.class);
					    }
						
						getContentResolver().notifyChange(ObserverConstants.LOGIN_SUCCESS, null);
						enterActivity(MainFragmentAct.class);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});
			  getNameRequest.setIsParseJson(false);
				executeRequest(getNameRequest);
		} catch (Exception e) {
		     e.printStackTrace();
		}
		   
	}
	
	private boolean checkInfo() {
		String username = login_usename.getText().toString().trim();

		String password = login_password.getText().toString().trim();
		if (TextUtils.isEmpty(username)) {
			UIUtil.showToast(LoginAct.this,
					getResources().getString(R.string.phonenumber));
			return false;
		} else if (TextUtils.isEmpty(password)) {
			UIUtil.showToast(LoginAct.this,
					getResources().getString(R.string.password));
			return false;
		}
		return true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		VolleyManager.cancelRequest(this);
	}
	
	/**
	 * 网络出现错误的时�?
	 */
//	private void doErrorNet(){
//		User user =  UserKeeper.getCurrentUser(LoginAct.this);
//			if(user != null){
//				user.getIUserInstance().setUser(user);
//			Intent intent=new Intent(context, FrameAct.class);
//			startActivity(intent);
//			finish();
//			}
//	}
	private TextWatcher mTextWatcher = new TextWatcher() {
		private int editStart;
		private int editEnd;
		private CharSequence temp;  

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			temp=s;
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void afterTextChanged(Editable s) {
			editStart = login_usename.getSelectionStart();
			editEnd = login_usename.getSelectionEnd();
			login_usename.removeTextChangedListener(mTextWatcher);
				if(Pattern.matches(Constants.PHONE_MATCH, temp)){
				chenck_phone_img.setVisibility(View.VISIBLE);
				}else{
					chenck_phone_img.setVisibility(View.GONE);
				}
			if (temp.length()!=0) {
				chenck_phone_text.setVisibility(View.GONE);
			}else{
				chenck_phone_text.setVisibility(View.VISIBLE);
			}
			
			login_usename.setText(s);
			login_usename.setSelection(editStart);
			
			login_usename.addTextChangedListener(mTextWatcher);
		}
	};
	
	private TextWatcher PsswordTextWatcher=new TextWatcher() {
		private int editEnd;
		private int editStart;
		private CharSequence temp;
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			temp=s;
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			
		}
		
		@Override
		public void afterTextChanged(Editable s) {
			editStart = login_password.getSelectionStart();
			editEnd = login_password.getSelectionEnd();
			login_password.removeTextChangedListener(PsswordTextWatcher);
				if(Pattern.matches(com.xywy.bloodandroid.util.Constants.PASSWORD, temp)){
				chenck_password_img.setVisibility(View.VISIBLE);
				}else{
					chenck_password_img.setVisibility(View.GONE);
				}
			if (temp.length()!=0) {
				chenck_password_text.setVisibility(View.GONE);
			}else{
				chenck_password_text.setVisibility(View.VISIBLE);
			}
			
			login_password.setText(s);
			login_password.setSelection(editStart);
			
			login_password.addTextChangedListener(PsswordTextWatcher);
		}
	};
	private TextView register;
	private TextView chenck_phone_text;
	private ImageView chenck_phone_img;
	private TextView chenck_password_text;
	private ImageView chenck_password_img;
}
